import os
import json
import time
import re
from kubernetes import client, config, stream
import urllib3
import hashlib
import yaml


# 禁用 InsecureRequestWarning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class KubernetsAPI:
    def __init__(self, kubeconfig=None,token=None,apiServer=None):
        if os.path.isfile(os.path.expanduser("~/.kube/config")): # 如果存在默认的 kubeconfig 文件，加载本地配置
            print("本地调用")
            config.load_kube_config()
        elif kubeconfig:
            kubeconfig_dict = self.parse_kubeconfig(kubeconfig) # 解析 kubeconfig 内容并创建配置对象
            config.load_kube_config_from_dict(kubeconfig_dict) # 使用 config.load_kube_config_from_dict 创建 kubeconfig 配置对象
        elif token:
            kubeconfig = client.Configuration()
            kubeconfig.host =  apiServer  # APISERVER 地址
            kubeconfig.verify_ssl = False
            kubeconfig.api_key = {"authorization": f"Bearer {token}"}
            client.Configuration.set_default(kubeconfig)
        else :
            pass
        

    def parse_kubeconfig(self,kubeconfig_content):
        try:
            kubeconfig_dict = yaml.safe_load(kubeconfig_content)
            return kubeconfig_dict
        except yaml.YAMLError as e:
            raise Exception(f"Error parsing kubeconfig content: {str(e)}")
    
    def verify_login(self):
        try:
          
            self.core_api = client.CoreV1Api()
            self.apps_api = client.AppsV1Api()
            self.core_api.list_namespace()
            print("api接口调用验证成功.")
            return True
        except Exception as e:
            print(f"api接口调用验证失败.: {str(e)}")
            return False


if __name__ == "__main__":
    K8s = KubernetsAPI()
    K8s.verify_login()


    #     pod_list = self.core_api.list_pod_for_all_namespaces(watch=False)
    #     print(pod_list)
